package com.ad.pet.app.account.order.view;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.ResourcesUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.PhotoManager;
import com.ad.pet.models.remote.account.PicPath;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.functions.Action1;

/**
 * 确认收货对话框
 * Created by SEELE on 2019/1/30.
 */

public class ConfirmReciveDialog extends Dialog {
    private OnSubmitLinstener mOnSubmitLinstener;
    private int screenWidth;

    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    RxDisposable mRxDisposable;
    private File mFile;


    FileUtil mFileUtil;


    PermissionManager mPermissionManager;
//    private int maxPhoto = 5;


    private ArrayList<PicPath> mPhotos;
    private MyAdapter mAdapter;
    private android.support.v4.app.Fragment mFragment;
    private RatingBar mPrgressBar;
    private EditText mEtContent;

    private final PicPath mInitPicPath;

    public ConfirmReciveDialog(@NonNull Context context, android.support.v4.app.Fragment fragment) {
        super(context, R.style.custom_dialog_style);

        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        this.mFragment = fragment;
        Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + context.getResources().getResourcePackageName(R.drawable.ic_upload_img) + "/"
                + context.getResources().getResourceTypeName(R.drawable.ic_upload_img) + "/"
                + context.getResources().getResourceEntryName(R.drawable.ic_upload_img));
        mInitPicPath = new PicPath(9999999999999999L, uri.toString(), null);
        initViews(context);
    }

    private void initViews(final Context context) {
        mRxDisposable = new RxDisposable();
        mFileUtil = new FileUtil(context, new ResourcesUtil(context));
        mPermissionManager = new PermissionManager((Activity) context, ToastUtil.getToastUtil(), new ResourcesUtil(context));
        mPermissionManager.setRxPermissions(new RxPermissions((Activity) context));

        mDialogView = LayoutInflater.from(context).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButOpen = mDialogView.findViewById(R.id.but_open);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);



        mPhotoDialog = new BottomSheetDialog(context);
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);


        View view = View.inflate(context, R.layout.layout_comfirm_recive, null);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        Button btnCancel = view.findViewById(R.id.btn_ok);
        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        mPrgressBar = view.findViewById(R.id.rb_normal);
        mEtContent = view.findViewById(R.id.et_aaa);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnSubmitLinstener.onSubmit(String.valueOf(mPrgressBar.getRating()), mEtContent.getText().toString(),null);
            }
        });

        mPhotos = new ArrayList<>();
        initPhotos();
        mAdapter = new MyAdapter(mPhotos);
        recyclerView.setLayoutManager(new GridLayoutManager(context, 5));
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnAddItemListener(new OnAddPhotoItemLinstener() {
            @Override
            public void onAdd(int position) {
//                if (mPhotos.size() >= 5) {
//                    ToastUtil.getToastUtil().showShort(context.getString(R.string.most_chose_4));
//                    return;
//                }
                BottomSheetUtil.collapsedDialog(mDialogView);
                mPhotoDialog.show();

            }
        });
        mAdapter.setOnDeleteItemListener(new OnDeleteItemListener() {
            @Override
            public void onDelete(int position) {
                mPhotos.remove(position);
                if (mPhotos.size()==4&&mPhotos.get(0).getFile()!=null){
                    mPhotos.add(mInitPicPath);
                    Collections.sort(mPhotos);
                }
                mAdapter.notifyDataSetChanged();

            }
        });

        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        //打开相机
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                //打开相机
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        mFile = new File(mFileUtil.getRootDir(), System.currentTimeMillis() + ".jpg");
                        //打开相机
//                        if (maxPhoto - mAdapter.getData().size() - 1 > 0) {
                            PhotoManager.openCamera(mFragment, mFile, PhotoManager.REQUEST_CODE_OPEN_CAMERA);

//                        } else {
//                            ToastUtil.getToastUtil().showShort(context.getString(R.string.most_chose_4));
//                        }
                    }
                }, context.getString(R.string.camera), Manifest.permission.CAMERA));
            }
        });

        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Navigation.goPhotoLoaderActivity(mFragment, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
                    }
                }, context.getString(R.string.storage), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE));
            }
        });

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        setContentView(view);


        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        Logger.e("screew:" + screenWidth);
        lp.width = (screenWidth * 8 / 10); // 设置宽度
//        lp.height = (int)(lp.width*1.7);
        this.getWindow().setAttributes(lp);
        window.setGravity(Gravity.CENTER);


    }

    private void initPhotos() {
        mPhotos.add(mInitPicPath);
        Collections.sort(mPhotos);
    }

    public void setOnSubmitLinstener(OnSubmitLinstener onSubmitLinstener) {
        mOnSubmitLinstener = onSubmitLinstener;
    }

    class MyAdapter extends BaseQuickAdapter<PicPath, BaseViewHolder> {
//        int mustCount = 5;
        private OnDeleteItemListener mOnDeleteItemListener;
        private OnAddPhotoItemLinstener mOnAddPhotoItemLinstener;

        public MyAdapter(@Nullable List<PicPath> data) {
            super(R.layout.item_photo_suggest_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final PicPath item) {
            ImageView ivDelete = helper.getView(R.id.iv_delete);
            ImageView ivPhoto = helper.getView(R.id.iv_photo);
            ImageView ivUpdate = helper.getView(R.id.iv_update);
            if (item.getId() != 9999999999999999L) {
                GlideUtil.load(mContext, item.getPic_path(), ivPhoto);
            }
            ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnDeleteItemListener.onDelete(helper.getLayoutPosition());
                }
            });
            if (item.getId() == 9999999999999999L) {
                ivDelete.setVisibility(View.GONE);
                ivUpdate.setVisibility(View.VISIBLE);
                ivPhoto.setVisibility(View.GONE);
                ivUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnAddPhotoItemLinstener.onAdd(helper.getLayoutPosition());
                    }
                });
            } else {
                ivDelete.setVisibility(View.VISIBLE);
                ivUpdate.setVisibility(View.GONE);
                ivPhoto.setVisibility(View.VISIBLE);
                ivUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Navigation.goPhotoLoaderActivity((Activity) mContext, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
//                        ArrayList<String> list = new ArrayList();
//                        for (int i = 0; i < mData.size(); i++) {
//                            list.add( mData.get(i).getImagePath());
//                        }
//                        Navigation.goPhotoViewPager(mContext, list, helper.getLayoutPosition());
                    }
                });
            }
//            if (mustCount == helper.getLayoutPosition()) {
//                ivUpdate.setVisibility(View.GONE);
//            } else {
//                ivUpdate.setVisibility(View.VISIBLE);
//            }


        }

        public void setOnDeleteItemListener(OnDeleteItemListener listener) {
            if (listener != null) {
                this.mOnDeleteItemListener = listener;
            }
        }

        public void setOnAddItemListener(OnAddPhotoItemLinstener listener) {
            if (listener != null) {
                this.mOnAddPhotoItemLinstener = listener;
            }
        }


    }

    public interface OnDeleteItemListener {
        void onDelete(int position);
    }

    public interface OnAddPhotoItemLinstener {
        void onAdd(int position);
    }

    public void onSetFiles(File file) {
        Logger.e("setThread:"+Thread.currentThread());
        if (mPhotos.size()==5){
            mPhotos.set(0,new PicPath(System.currentTimeMillis(),file.toURI().getPath(),file));
            Collections.sort(mPhotos);
        }else {
            mPhotos.add(new PicPath(System.currentTimeMillis(), file.toURI().getPath(), file));
        }

        mAdapter.notifyDataSetChanged();
    }
    public ArrayList<PicPath> getPhotos() {
        return mPhotos;
    }
    public void clearData(){
        mPhotos.clear();
        initPhotos();
        mAdapter.notifyDataSetChanged();
        mEtContent.setText("");
        mPrgressBar.setRating(5);
    }

    public File getFile() {
        return mFile;
    }
}
